﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RM.Common;
using System.Text;
using System.Web.Security;
using RM.DBUtility;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;

namespace RM.Web
{
    public partial class Login : PageBase
    {
        //private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        protected void Page_Load(object sender, EventArgs e)
        {
            //errormsg.InnerHtml = "<strong><font color=#D9534F>请输入用户名和密码！</font></strong>";
            errormsg.InnerHtml = String.Format(" 三运用信息平台(OA) <strong><font color=red>v{0}</font></strong>", GetProductVersion());


            BLL.RMDept bll = new BLL.RMDept();
            Model.RMDept model = bll.GetModel(1);
            bll.Delete(5);

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string UserName = this.txtUserName.Text.Trim();//这里录入的可以是用户名（姓名）也可以是工资号
            string Password = this.txtPassword.Text.Trim();

            string ip = DTRequest.GetIP();
            BLL.RMUsers bll = new BLL.RMUsers();
            Model.RMUsers model = bll.GetLoginModel(UserName,UserName);
            BLL.RMLog bllRMLog = new BLL.RMLog();
            if (model != null)
            {
                if (PasswordUtil.ComparePasswords(model.Password, Password))
                {
                    if (!model.IsEnable)
                    {
                        MessageBox.Show(this, "账户未启用，请联系管理员开通！");
                        //return;                        
                    }
                    else
                    {
                        //MessageBox.Show(this, "登录成功！");
                        //写入日志                        
                        bllRMLog.Add(DateTime.Now, model.UserName, string.Format("登录成功：用户{0}[{1}]", model.UserName, model.Salary));
                        LoginSuccess(model);
                        return;

                    }
                }
                else
                {
                    //写入日志                    
                    bllRMLog.Add(DateTime.Now, UserName, string.Format("登录失败：用户{0}",UserName));
                    MessageBox.Show(this, "用户名或者密码错误！");
                    return;
                }
            }
            else
            {
                bllRMLog.Add(DateTime.Now, UserName, string.Format("登录失败：用户{0}", UserName));
                MessageBox.Show(this, "用户名或者密码错误！");
                return;
            }            
        }

        #region 私有
        private void LoginSuccess(Model.RMUsers model)
        {
            string szSQL = "select roleid from x_roleuser where userid='" + model.Id + "'";
            StringBuilder sb = new StringBuilder();
            DataSet ds = DbHelperSQL.Query(szSQL);
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                sb.AppendFormat("{0},", ds.Tables[0].Rows[i]["roleid"].ToString());
            }
            string roleIds = sb.ToString().TrimEnd(',');

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                model.UserName,
                DateTime.Now,
                DateTime.Now.AddMinutes(120),
                true,
                roleIds,
                FormsAuthentication.FormsCookiePath);
            string hashTicket = FormsAuthentication.Encrypt(ticket);
            HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
            userCookie.HttpOnly = true;
            userCookie.Expires = DateTime.Now.AddMinutes(120);
            Response.Cookies.Add(userCookie);
            Response.Redirect(FormsAuthentication.DefaultUrl);
        }
        #endregion

        #region 无用代码，暂时先放着，回头删除，我测试用的。
        private void Showinfo()
        {            
            StringBuilder strSql = new StringBuilder();
            BLL.RMRole bll = new BLL.RMRole();
            List<Model.RMRole> rolenames = bll.GetAllModel();
            foreach (Model.RMRole rolename in rolenames)
            {
                strSql.AppendFormat("{0},", rolename.Name);
            }
            lblInfo.InnerHtml = "<strong><font color=red>" + strSql.ToString().TrimEnd(',') + "</font></strong>";
        }
        #endregion



        #region 遍历获取类的属性及属性的值
        private string getProperties<T>(T t)
        {
            string tStr = string.Empty;
            if (t == null)
            {
                return tStr;
            }

            System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
            if (properties.Length <= 0)
            {
                return tStr;
            }
            foreach (System.Reflection.PropertyInfo item in properties)
            {
                string name = item.Name;
                object value = item.GetValue(t, null);
                if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
                {
                    tStr += string.Format("{0}:{1}", name, value);
                }
                else
                {
                    getProperties(value);
                }
            }
            return tStr;
        }

        /// <summary>
        /// 获取非泛型集合类的ArrayList
        /// </summary>
        /// <returns></returns>
        public List<Model.RMRole> getRoleNames()
        {
            List<Model.RMRole> list = new List<Model.RMRole>();
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * from X_Role");
            SqlDataReader dr = DbHelperSQL.ExecuteReader(strSql.ToString());
            while (dr.Read())
            {
                Model.RMRole model = new Model.RMRole();
                model.Id = int.Parse(dr["id"].ToString());
                model.Name = dr["name"].ToString();
                model.Remark = dr["remark"].ToString();
                list.Add(model);
            }
            dr.Close();
            return list;
        }



        #endregion


    }
}